<?php
/**
 * @copyright	Copyright (C) 2009-2012 ACYBA SARL - All rights reserved.
 * @license		http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
 */
defined('_JEXEC') or die('Restricted access');
?>
<?php

class MailchimpController extends JController{
	function add(){
		$app = JFactory::getApplication();
		$email = JRequest::getVar('email');
		$api_key =  JRequest::getVar('api_key');
		$list_id = JRequest::getVar('list_id');
		
		//echo $email;die;
		if($this->storeAddress($email,$api_key,$list_id))
			$this->setRedirect(JRoute::_('index.php?option=com_acymailing&ctrl=user&task=complete'), false);
		else $this->setRedirect(JRoute::_('index.php?option=com_acymailing&ctrl=user&task=fail'), false);	
	}
	function storeAddress($email,$api_key,$list_id){
		
		// Validation
		if(!$email){ return false; } 

		if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $email)) {
			return false; 
		}
		//echo "test";die;
		require_once(ACYMAILING_ROOT.DS.'components'.DS.ACYMAILING_COMPONENT.DS.'inc'.DS.'mcapi'.DS.'MCAPI.class.php');

		// grab an API Key from http://admin.mailchimp.com/account/api/
		$api = new MCAPI($api_key);
		
		// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
		// Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
		//$list_id = "06e7b6dc95";

		if($api->listSubscribe($list_id, $email, '') === true) {
			// It worked!	
			//echo $email;die;
			return true;
		}else{
			// An error ocurred, return error message	
			return false;
		}
	
	}
}